package com.mjh.action;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.json.simple.JSONObject;
import com.mjh.comm.Constant;
import com.mjh.config.GlobalConfig;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ImageUploadAction extends ActionSupport{

	private static final long serialVersionUID = -6089133711830975045L;
	public static Logger log = Logger.getLogger(ImageUploadAction.class);
	
	private String contentType;
    private File imgFile;
    private String fileName;
    private String imgWidth;
    private String imgHeight;
    
    private String iscustomFolder;
    private String uploadFolder;
    
    @SuppressWarnings("unchecked")
	public String upload() {
		JSONObject result = new JSONObject();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html; charset=UTF-8");
		//忽略result参数，直接返回内容
		ActionContext.getContext().getActionInvocation().getProxy().setExecuteResult(false);
		try {
			String folder;
			System.out.println(uploadFolder);
			if(!"true".equals(iscustomFolder)){
				folder = getStoreFolder(Constant.SERVLET_CONTEXT);
			} else {
				folder = GlobalConfig.getSysConfig().getImgFolder() + File.separator + uploadFolder;
			} 
			String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
			String imgPath = File.separator + folder + File.separator + fileRename() + suffix;
			File imgOutFile = new File(Constant.SERVLET_CONTEXT, imgPath);
			
			if(NumberUtils.toInt(imgWidth) != 0 && NumberUtils.toInt(imgHeight) != 0){
				scaleImage(imgFile, imgOutFile, suffix.substring(1));
			} else {
				byte[] buff = new byte[1024];
				int len;
				FileInputStream in = new FileInputStream(imgFile);
				FileOutputStream out = new FileOutputStream(imgOutFile);
				while((len = in.read(buff)) != -1){
					out.write(buff, 0, len);
				}
				in.close();
				out.close();
			}
			result.put("error", 0);
			result.put("url", imgPath.replaceAll("\\\\", "/"));
			response.getWriter().write(result.toJSONString());
			
		} catch (IOException e) {
			log.error(e.getMessage());
			result.put("error", 1);
			result.put("message", "上传失败：" + e.getMessage());
			try {
				response.getWriter().write(result.toJSONString());
			} catch (IOException e1) {}
		}
		return SUCCESS;
	}
	
	private String fileRename(){
		return String.valueOf(System.currentTimeMillis());
	}
	
	private String getStoreFolder(String parent){
		Calendar calendar = Calendar.getInstance();
		String year = String.valueOf(calendar.get(Calendar.YEAR));
		String month = String.valueOf(calendar.get(Calendar.MONTH));
		StringBuilder folderPath = new StringBuilder(); 
		folderPath.append(GlobalConfig.getSysConfig().getImgFolder());
		folderPath.append(File.separator);
		folderPath.append(year);
		folderPath.append(File.separator);
		folderPath.append(month);
		File folder = new File(parent, folderPath.toString());
		if(!folder.exists()){
			folder.mkdirs();
		}
		return folderPath.toString();
	}
	
	/**
	 * 缩小原图,这里有问题，如果上传的是透明底的图片，会变成黑色底
	 * @param source
	 * @param dest
	 * @param imageType
	 * @throws IOException
	 */
	private void scaleImage(File source, File dest, String imageType) throws IOException{
		BufferedImage sourceImg = ImageIO.read(source);
		BufferedImage destImg = new BufferedImage(NumberUtils.toInt(this.imgWidth), NumberUtils.toInt(this.imgHeight), BufferedImage.TYPE_INT_RGB);
		Image scaleImg = sourceImg.getScaledInstance(NumberUtils.toInt(this.imgWidth), NumberUtils.toInt(this.imgHeight), Image.SCALE_SMOOTH);
		Graphics g = destImg.getGraphics();
		g.drawImage(scaleImg, 0, 0, new ImageObserver() {
			public boolean imageUpdate(Image paramImage, int paramInt1, int paramInt2,
					int paramInt3, int paramInt4, int paramInt5) {
				//这里一定要返回true，否则不会将图像写进去
				return true;
			}
		});
		ImageIO.write(destImg, imageType, dest);
	}
	
	public String getImgFileFileName() {
        return fileName;
    }
    public void setImgFileFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getImgFileContentType() {
        return contentType;
    }
    public void setImgFileContentType(String contentType) {
        this.contentType = contentType;
    }

    public File getImgFile() {
        return imgFile;
    }
    public void setImgFile(File upload) {
        this.imgFile = upload;
    }

	public String getImgWidth() {
		return imgWidth;
	}

	public void setImgWidth(String imgWidth) {
		this.imgWidth = imgWidth;
	}

	public String getImgHeight() {
		return imgHeight;
	}

	public void setImgHeight(String imgHeight) {
		this.imgHeight = imgHeight;
	}

	public String getUploadFolder() {
		return uploadFolder;
	}

	public void setUploadFolder(String uploadFolder) {
		this.uploadFolder = uploadFolder;
	}

	public String getIscustomFolder() {
		return iscustomFolder;
	}

	public void setIscustomFolder(String iscustomFolder) {
		this.iscustomFolder = iscustomFolder;
	}

}
